import { Tag } from "@/stores/types";
import { useApiFetch, ApiResponse } from "@/composables/useApiFetch";

export const useTagsStore = defineStore(
  "tags",
  () => {
    // 所有 Tags
    const tags = ref<Tag[]>([]);

    // 预定义 Tags
    const predefineTags = computed(() =>
      tags.value.filter((tag) => tag.ownerId === null),
    );

    // 自定义 Tags
    const customTags = computed(() =>
      tags.value.filter((tag) => tag.ownerId != null),
    );

    const load = () => {
      // 向服务器请求 tags
      const { data } = useApiFetch("/user/tags").json<ApiResponse<Tag>>();
      watch(data, () => {
        if (data.value?.success) {
          // 所有 Tags
          tags.value = data.value.query.results;
        }
      });
    };

    const $reset = () => {
      tags.value = [];
    };

    // new tag
    const newTag = async (name: string) => {
      const { data } = await useApiFetch("/user/tags")
        .post({ name })
        .json<ApiResponse<Tag>>();
      if (data.value?.success) {
        tags.value.push(data.value.object);
      }
      return data;
    };

    return {
      tags,
      predefineTags,
      customTags,
      newTag,
      load,
      $reset,
    };
  },
  {
    persist: {
      storage: sessionStorage,
    },
  },
);
